//
//  JYUserAccount.swift
//  01.weibo
//
//  Created by 谢玉锋 on 16/7/12.
//  Copyright © 2016年 itheima.cn. All rights reserved.

//授权后返回的数据(账号信息):将其保存

/*
1.plist: NSArray/NSDictionary: writeToFile
2.偏好设置: NSUserDefaults: key -> value, 小数据, 国际化 12语言
3.NSCoding: 归档和解档: 对象
4.SQLite: 数据
5.CoreData: SQLite, 内存,xml
*/

import UIKit

class JYUserAccount: NSObject,NSCoding {

    var access_token: String?
//  基本数据类型不要定义为可选,定义为可选,kvc找不到这个属性
    var expires_in: NSTimeInterval = 0 {
        //属性检测器 (属性值改变时,会来调用)
        didSet {
        expires_inDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }

    //double不好计算,所以转成date
    var expires_inDate: NSDate?
    //用户id
    var uid: String?
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像地址（大图）180×180像素
    var avatar_large: String?
    
    init(dict: [String:AnyObject]) {
        // 在super.init之前需要给属性赋值,否则将属性定义为可选
        super.init()
        // 注意这个方法需要放在 super.init() 之后,因为super.init()后对象才创建完成,才能调用对象里面的方法
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
//        JYPrint("key: \(key)")
    }
    
    //如果不记得,在CustomStringConvertible协议中找
    override var description: String {
        get {
          return "access_token: \(access_token) ,expires_in: \(expires_in) ,uid: \(uid), expires_inDate: \(expires_inDate) screen_name:\(screen_name), avatar_large:\(avatar_large) "
        }
    }
    
    //归档和解档 (遵守协议 )
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as Double
        expires_inDate = aDecoder.decodeObjectForKey("expires_inDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_inDate, forKey:"expires_inDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name,forKey: "screen_name")
        aCoder.encodeObject(avatar_large,forKey: "avatar_large")
    }
}



